package org.xx.armory.web;

import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;

public final class PathUtils {
    private static final char DIRECTORY_SEPARATOR = '/';
    private static final String PARENT_DIRECTORY = "..";

    private PathUtils() {
    }

    public static String join(
            String first,
            String... more
    ) {
        first = StringUtils.trimToEmpty(first);
        if (first.isEmpty() && more == null) {
            return "";
        } else {
            StringBuilder buf = new StringBuilder(first);
            if (more != null) {
                Arrays.stream(more).map((s) -> s == null ? "" : s.trim())
                      .filter((s) -> !s.isEmpty())
                      .forEach((s) -> {
                          if (s.charAt(0) != DIRECTORY_SEPARATOR) {
                              buf.append(DIRECTORY_SEPARATOR);
                          }

                          buf.append(s);
                          int lp = buf.length() - 1;
                          if (buf.charAt(lp) == DIRECTORY_SEPARATOR) {
                              buf.deleteCharAt(lp);
                          }

                      });
            }

            if (buf.length() > 0 && buf.charAt(0) != DIRECTORY_SEPARATOR) {
                buf.insert(0, DIRECTORY_SEPARATOR);
            }

            return buf.toString();
        }
    }

    public static String relative(
            String src,
            String dst
    ) {
        src = StringUtils.trimToEmpty(src);
        dst = StringUtils.trimToEmpty(dst);
        if (dst.length() > 0 && dst.charAt(0) != DIRECTORY_SEPARATOR) {
            return dst;
        } else {
            final StringBuilder buf = new StringBuilder();
            final String[] part1 = src.split("/");
            final String[] part2 = dst.split("/");
            final int c1 = part1.length;
            final int c2 = part2.length;
            final int c = Math.max(c1, c2);
            int k = -1;

            int i;
            for (i = 0; i < c; ++i) {
                String p1 = i < c1 ? part1[i] : "";
                String p2 = i < c2 ? part2[i] : "";
                if (!p1.equals(p2)) {
                    k = i;
                    break;
                }
            }

            if (k == -1) {
                return part2.length == 0 ? "" : part2[part2.length - 1];
            } else {
                for (i = k; i < c1 - 1; ++i) {
                    if (i > k) {
                        buf.append('/');
                    }

                    buf.append(PARENT_DIRECTORY);
                }

                for (i = k; i < c2; ++i) {
                    if (buf.length() != 0) {
                        buf.append(DIRECTORY_SEPARATOR);
                    }

                    buf.append(part2[i]);
                }

                return buf.toString();
            }
        }
    }
}
